const express = require('express');
const app = express();

// ejs
const ejs = require('ejs');
app.set('view engine','ejs');
app.set('views','./views');
// body-parser
const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({extended:false}));

const cookieParser = require('cookie-parser');
app.use(cookieParser());
//静态资源
app.use(express.static(__dirname + '/public'));
// 导入数据
let data = require('./data/data.json');


// 路由配置
app.get('/index', (request, response)=>{
    response.render('index.ejs',{data});
})
app.get('/content/:id', (request, response)=>{
    let id = request.params.id;
    let result = data.find(item=>{
        return item.id == id;
    })
    console.log(result);
    response.render('content',{result});    
})

app.get('/login', (request, response)=>{
    response.render('login.ejs',{name:'yuonly'})
})
app.post('/login',(request, response)=>{
    console.log(request.body);
})

// 设置cookie
app.get('/set-cookie',(request, response)=>{
    response.cookie('username','yuonly');
    response.cookie('email','xxxx@163.com',{maxAge:60*1000});
    response.send('登录成功');
})
// 读取cookie
app.get('/get-cookie', (request, response)=>{
    console.log(request.cookies);
    response.send('get-cookie-page');
})
// 清楚cookie
app.get('/clear-cookie', (request, response)=>{
    console.log('clear-cookie');
    response.clearCookie('username');
    response.clearCookie('email');
    response.send('clear-cookie');
})

// 监听
app.listen(80,()=>{
    console.log('server run at 80');
})